package com.yonyou.gmmc.common.sms;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.marketing.common.FrameHttpUtil;

/**
 * 发送短信的工具类
 * 
 * @author qianjs163@163.com 2017年3月17日 下午4:49:33
 */
public class SmsHttpClient {

    private static Logger logger = Logger.getLogger(SmsHttpClient.class);

    /**
     * 发送短信
     * 
     * @auther qianjs163@163.com 2017年3月17日 下午4:51:35
     * @param phone
     * @param content
     * @return
     */
    public static String sendSms(String phone, String content,String smsPass ,String smsKey ,String SMS_CDKEY,String SMS_PASS, String SMS_BASEURL) {
        if (smsPass.equals("YONYOU") && smsKey.equals("GMMC")){
//            logger.info("开始发送短信！！");logger.info("电话：" + phone);
//            logger.info("发送的内容：" + content);
            try {
                content = URLEncoder.encode(content, "UTF-8");
            } catch (UnsupportedEncodingException ex) {
                logger.warn("exception happened while encode the message:{}!", ex);
            }
            String id = String.valueOf(new Date().getTime());
            Map<String, String> map = new LinkedHashMap<>();
            map.put("cdkey", SMS_CDKEY);
            map.put("password", SMS_PASS);
            map.put("phone", phone);
            map.put("message", content);
            map.put("seqid", id);
//            logger.info("参数为："+map);
            String param = FrameHttpUtil.getParams("get", map);
            String url = SMS_BASEURL;
            logger.info("发送短信的url为："+url);
            String result = FrameHttpUtil.sendGet(url, param).trim();

            if (null != result && !"".equals(result)) {
                logger.info("短信平台有返回值》》》》》》" + result);
                return xmlMt(result);
            }
            return null;
        }else{
            return null;
        }
        
    }

    // 解析下发response
    public static String xmlMt(String response) {
        String result = "0";
        Document document = null;
        try {
            document = DocumentHelper.parseText(response);
        } catch (DocumentException e) {
            logger.error(e.getMessage(), e);
            return "-250";
        }
        if (document != null) {
            Element root = document.getRootElement();
            result = root.elementText("error");
            if (null == result || "".equals(result)) {
                return "-250";
            }
        }

        return "0";
    }
}
